#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/20 18:03
# @Author  : Tom_zc
# @FileName: majun_helper.py
# @Software: PyCharm
import base64
import hashlib
import hmac
import time
import logging

import request_handler

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


class SCAHelper:
    scan_url = "{}/gateway/openlibing-sca/scan/pr"
    scan_result_url = "{}/gateway/openlibing-sca/scan/result?scanId={}"

    repo_exist_failed_code = "the repo already existed"

    def __init__(self, appId, secretKey, domain, request_handler=request_handler.RequestHandler()):
        self.appId = appId
        self.appKey = secretKey
        self.domain = domain
        self.request_handler = request_handler

    def refresh_sign(self, timestamp):
        hmac_string = self.appId + timestamp
        hmac_hash = hmac.new(self.appKey.encode(), hmac_string.encode(), digestmod=hashlib.sha256)
        hmac_base64 = base64.b64encode(hmac_hash.digest()).decode()
        return hmac_base64

    def add_repo(self, pr_url):
        timestamp = str(int(time.time() * 1000))
        headers = {
            "Content-Type": "application/json",
            "accountid": self.appId,
            "timestamp": timestamp,
            "sign": self.refresh_sign(timestamp)
        }
        data = {
            "prUrl": pr_url,
            "projectName": "openUBMC"
        }
        _, resp = self.request_handler.post(self.scan_url.format(self.domain), json_data=data, headers=headers)
        if not str(resp.get("code")).startswith("20"):
            raise Exception("create task failed:{}".format(resp.get("message")))
        return resp["data"]

    def check_task(self, task_id):
        count = 0
        while True:
            timestamp = str(int(time.time() * 1000))
            headers = {
                "Content-Type": "application/json",
                "accountid": self.appId,
                "timestamp": timestamp,
                "sign": self.refresh_sign(timestamp)
            }
            data = {
                "scanId": task_id
            }
            resp = self.request_handler.get(self.scan_result_url.format(self.domain, task_id), headers=headers)
            response = resp["data"]
            if str(resp.get("code")).startswith("20"):
                logging.info("status is:{}".format(response))
                if response["state"] == "success":
                    if response["unconfirmedFileNum"] == 0:
                        return "PASS", response["prResult"]
                    return "Failed", response["prResult"]
                elif response["state"] == "failure":
                    return "Failed", response["prResult"]
                elif response["state"] == "scanning":
                    logging.info("status is:{}".format(response["state"]))
                    count += 1
                    time.sleep(5)
            else:
                return "Failed", response["message"]

            if count > 10 * 60 / 5:
                return "Timeout", response["message"]
